package com.servlet;

import com.Service.Impl.UserServiceImpl;
import com.Service.UserService;
import com.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/replaceImg")
@MultipartConfig(maxFileSize = 500000)
public class replaceImgServlet extends HttpServlet {

    private UserService service = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户从页面传递的文件对象
        Part headImg = req.getPart("headImg");
        if (!headImg.getContentType().startsWith("image/")) {
            req.setAttribute("headImgMsg", "文件类型不匹配");
            req.getRequestDispatcher("/replaceImg.jsp").forward(req, resp);
            return;
        }
        //使用UUID随机生成新的文件名
        String name = headImg.getSubmittedFileName();
        String substring = name.substring(name.lastIndexOf("."));
        String newname = UUID.randomUUID().toString() + substring;
        String path = req.getServletContext().getRealPath("/") + newname;
        //获取登录后共享在指定会话域独享中的对象
        //强转的原因:需要通过当前对象调用方法,给数据库中指定列设置值
        User user_in_session = (User) req.getSession().getAttribute("USER_IN_SESSION");
        if (user_in_session != null) {
            //通过User对象调用set方法,将图片设置给指定字段
            user_in_session.setHeading(newname);
            service.editHeadImg(user_in_session);
            //将数据写入数据库中
            headImg.write(path);
            //上传成功后,重定向到/shuihu发送请求
            resp.sendRedirect("/shuihu");
        }else{
            //表示没有进行登录,跳转登录页面
            resp.sendRedirect("/login.jsp");
        }

    }
}
